package com.itheima.controller;

import com.itheima.pojo.*;
import com.itheima.service.UserService;
import com.itheima.utils.JwtUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@CrossOrigin
public class UserController {

    private final UserService userService;

    @GetMapping
    public Result page(PageQueryParam pageQueryParam) {
        PageResult<User> pageResult = userService.page(pageQueryParam);
        return Result.success(pageResult);
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        User userInfo = userService.login(user);
        if (!Objects.isNull(userInfo)) {
            Map<String, Object> map = new HashMap<>();
            map.put("id", userInfo.getId());
            map.put("name", userInfo.getName());
            String token = JwtUtils.generateJwt(map);
            LoginResult loginResult = new LoginResult(userInfo.getId(), userInfo.getName(), token);
            return Result.success(loginResult);
        }
        return Result.error(403,"连接超时，请重新登录！");
    }
}
